import { mToken } from '../../usbkey/mToken';
import { base64decode, base64encode } from '../../usbkey/base64';
import MLog from '../main-log';
const TAG = 'VerifyUtil';
export class VerifyUtil {
  private static token = new mToken('DataManagementPlugin');
  public static getLMDevice() {
    VerifyUtil.token.SOF_LoadLibrary(VerifyUtil.token.GM3000);
    const devices = VerifyUtil.token.SOF_EnumDevice();
    const deviceName = devices && devices.length > 0 ? devices[0] : null;
    if (deviceName) {
      VerifyUtil.token.SOF_GetDeviceInstance(deviceName, '');
    }
    return deviceName;
  }
  public static minusUseCount() {
    MLog.i(TAG, '执行使用次数减一');
    try {
      VerifyUtil.getUseCount().then((res) => {
        const devicdeName = VerifyUtil.getLMDevice();
        if (devicdeName) {
          MLog.i(TAG, '找到龙脉设备', devicdeName);
        }
        const fileName = VerifyUtil.getFileName();
        if (fileName) {
          MLog.i(TAG, '找到状态文件', fileName);
        }
        VerifyUtil.token.SOF_WriteFile(
          fileName,
          0,
          base64encode(JSON.stringify({ useCount: res - 1 }))
        );
        MLog.i(TAG, '执行使用次数减一成功');
      });
    } catch (err) {
      MLog.e(TAG, '执行使用次数减一失败', err);
    }
  }
  public static getFileName() {
    const fileList = VerifyUtil.token.SOF_EnumFiles();
    MLog.i(TAG, '文件列表', fileList);
    return fileList && fileList.length > 0 ? fileList[0] : null;
  }
  public static getUseCount(): Promise<number> {
    return new Promise((resolve, reject) => {
      try {
        const devicdeName = VerifyUtil.getLMDevice();
        if (!devicdeName) {
          reject('找不到龙脉设备');
        } else {
          MLog.i(TAG, '找到龙脉设备', devicdeName);
        }
        const fileName = VerifyUtil.getFileName();
        if (!fileName) {
          reject('找不到状态文件');
        } else {
          MLog.i(TAG, '找到状态文件', fileName);
        }
        const fileData: string = base64decode(
          VerifyUtil.token.SOF_ReadFile(fileName, 0, 0)
        );
        const data = fileData.slice(0, fileData.lastIndexOf('}') + 1);
        const dataJSON = JSON.parse(data);
        MLog.i(TAG, '解析文件成功', dataJSON);
        resolve(dataJSON['useCount'] ?? -1);
      } catch (e) {
        reject(e);
      }
    });
  }
  public static checkExpire(): Promise<string> {
    return new Promise((resolve, reject) => {
      MLog.i(TAG, '开始执行获取使用次数');
      VerifyUtil.getUseCount()
        .then((res) => {
          MLog.i(TAG, '获取使用次数成功', res);
          if (res >= 0) {
            resolve('');
          } else {
            reject();
          }
        })
        .catch((err) => {
          reject(err);
          MLog.e(TAG, '执行获取使用次数失败', err);
        });
    });
  }
}
